package root.electronclass.electronclass.ext

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction

/**
 *
 * @author Lokiy
 * @date 2023/1/14 15:13
 */

/**
 * 隐藏FragmentManager下的所有fragment
 */
fun FragmentManager.hideAll(fragmentTransaction: FragmentTransaction? = null): FragmentTransaction {
    val transaction = fragmentTransaction ?: beginTransaction()
    fragments.forEach { transaction.hide(it) }
    if (fragmentTransaction == null) {
        transaction.commit()
    }
    return transaction
}

/**
 * 显示fragment[clazz],如果有就显示，没有就先添加然后显示
 */
fun FragmentManager.show(id: Int, clazz: Class<out Fragment>, fragmentTransaction: FragmentTransaction? = null): FragmentTransaction {
    val transaction = fragmentTransaction ?: beginTransaction()
    val tag = clazz.simpleName
    val fragment = findFragmentByTag(tag) ?: clazz.newInstance().also { transaction.add(id, it, tag) }
    return transaction.show(fragment)

}